package ui;

import model.RedWine;
import model.Order;
import model.User;
import service.RedWineService;
import service.OrderService;
import service.UserService;
import factory.ServiceFactory;
import util.InputValidator;
import util.StringUtil;
import java.util.List;
import java.util.Scanner;

public abstract class UI { // 抽象UI类，定义通用方法和属性 完成人：姜凯严、尹佳杨 7/5
    protected RedWineService redWineService = ServiceFactory.getRedWineService();
    protected OrderService orderService = ServiceFactory.getOrderService();
    protected UserService userService = ServiceFactory.getUserService();

    public abstract void show();

    // 通用红酒列表打印方法
    protected void printRedWineList(List<RedWine> list) {
        if (list == null || list.isEmpty()) {
            System.out.println("未找到符合条件的红酒！");
            return;
        }
        System.out.println("+--------+------------------+------+--------+------------+------------+------------+");
        System.out.println("| 红酒ID |       酒名       | 库存 |  单价  |    国家    |    城市    |     县     |");
        System.out.println("+--------+------------------+------+--------+------------+------------+------------+");
        for (RedWine rw : list) {
            String name = rw.getName() != null ? rw.getName() : "";
            String country = rw.getCountry() != null ? rw.getCountry() : "";
            String city = rw.getCity() != null ? rw.getCity() : "";
            String county = rw.getCounty() != null ? rw.getCounty() : "";
            
            // 使用显示宽度处理，确保表格对齐
            String displayName = StringUtil.truncateByDisplayWidth(name, 16);
            String displayCountry = StringUtil.truncateByDisplayWidth(country, 10);
            String displayCity = StringUtil.truncateByDisplayWidth(city, 10);
            String displayCounty = StringUtil.truncateByDisplayWidth(county, 10);
            
            // 填充到固定显示宽度
            displayName = StringUtil.padToDisplayWidth(displayName, 16);
            displayCountry = StringUtil.padToDisplayWidth(displayCountry, 10);
            displayCity = StringUtil.padToDisplayWidth(displayCity, 10);
            displayCounty = StringUtil.padToDisplayWidth(displayCounty, 10);
            
            System.out.printf("| %-6d | %s | %-4d | %6.2f | %s | %s | %s |%n",
                    rw.getRedWineId(), displayName, rw.getStock(), rw.getPrice(),
                    displayCountry, displayCity, displayCounty);
            
            // 如果有内容被截断，在下一行显示完整信息
            boolean hasOverflow = false;
            if (StringUtil.getDisplayWidth(name) > 16) {
                System.out.printf("|        | 完整酒名: %-60s |%n", name);
                hasOverflow = true;
            }
            if (StringUtil.getDisplayWidth(country) > 10) {
                System.out.printf("|        | 完整国家: %-60s |%n", country);
                hasOverflow = true;
            }
            if (StringUtil.getDisplayWidth(city) > 10) {
                System.out.printf("|        | 完整城市: %-60s |%n", city);
                hasOverflow = true;
            }
            if (StringUtil.getDisplayWidth(county) > 10) {
                System.out.printf("|        | 完整县名: %-60s |%n", county);
                hasOverflow = true;
            }
            if (hasOverflow) {
                System.out.println("+--------+------------------+------+--------+------------+------------+------------+");
            }
        }
        System.out.println("+--------+------------------+------+--------+------------+------------+------------+");
    }

    // 通用红酒全部展示方法
    protected void listRedWines() {
        List<RedWine> list = redWineService.findAll();
        printRedWineList(list);
    }

    // 通用红酒筛选方法
    protected void filterRedWine(Scanner scanner) {
        System.out.println("---- 红酒筛选 ----");
        System.out.println("1. 按名字筛选");
        System.out.println("2. 按产地筛选");
        System.out.println("3. 按价格筛选");
        System.out.print("请选择筛选方式: ");
        String op = scanner.nextLine();
        if ("1".equals(op)) {
            System.out.print("请输入酒名关键字: ");
            String namePart = scanner.nextLine();
            List<RedWine> list = redWineService.findByNameLike(namePart);
            printRedWineList(list);
        } else if ("2".equals(op)) {
            System.out.print("请输入产地(国家/城市/县): ");
            String origin = scanner.nextLine();
            List<RedWine> list = redWineService.findByOrigin(origin);
            printRedWineList(list);
        } else if ("3".equals(op)) {
            // 使用InputValidator工具类进行价格范围校验
            Double[] priceRange = InputValidator.getValidPriceRange(scanner, 
                "请输入价格下限(可留空): ", "请输入价格上限(可留空): ");
            
            if (priceRange == null) {
                return; // 校验失败，直接返回
            }
            
            Double min = priceRange[0];
            Double max = priceRange[1];
            List<RedWine> list = redWineService.findByPriceRange(min, max);
            printRedWineList(list);
        }
    }

    // 通用订单打印方法（含用户名、红酒名称和金额显示）
    protected void printOrderList(List<Order> orders) {
        if (orders == null || orders.isEmpty()) {
            System.out.println("未找到符合条件的订单！");
            return;
        }
        
        System.out.println("+----------+--------+--------+----------+------+----------+------+----------+------------+");
        System.out.println("| 订单标识码 | 订单ID | 红酒ID |  用户名  | 数量 |   状态   | 线上 |  红酒名称  |   金额    |");
        System.out.println("+----------+--------+--------+----------+------+----------+------+----------+------------+");
        
        for (Order o : orders) {
            // 获取用户信息
            User user = userService.findById(o.getUserId());
            String username = user != null ? user.getUsername() : "未知用户";
            
            // 获取红酒信息
            RedWine redWine = redWineService.findById(o.getRedWineId());
            String wineName = redWine != null ? redWine.getName() : "未知";
            double amount = calculateOrderAmount(o);
            
            String status = o.getStatus().name();
            String displayStatus = StringUtil.truncateByDisplayWidth(status, 8);
            String displayWineName = StringUtil.truncateByDisplayWidth(wineName, 8);
            String displayUsername = StringUtil.truncateByDisplayWidth(username, 8);
            
            // 填充到固定显示宽度
            displayStatus = StringUtil.padToDisplayWidth(displayStatus, 8);
            displayWineName = StringUtil.padToDisplayWidth(displayWineName, 8);
            displayUsername = StringUtil.padToDisplayWidth(displayUsername, 8);
            
            System.out.printf("| %-8d | %-6d | %-6d | %s | %-4d | %s | %-4s | %s | %10.2f |%n", 
                o.getCode(), o.getOrderId(), o.getRedWineId(), displayUsername, o.getQuantity(), 
                displayStatus, o.isOnline() ? "是" : "否", displayWineName, amount);
            
            // 如果有内容被截断，在下一行显示完整信息
            boolean hasOverflow = false;
            if (StringUtil.getDisplayWidth(username) > 8) {
                System.out.printf("|          |        |        | 完整用户名: %-50s |%n", username);
                hasOverflow = true;
            }
            if (StringUtil.getDisplayWidth(wineName) > 8) {
                System.out.printf("|          |        |        | 完整红酒名: %-50s |%n", wineName);
                hasOverflow = true;
            }
            if (hasOverflow) {
                System.out.println("+----------+--------+--------+----------+------+----------+------+----------+------------+");
            }
        }
        System.out.println("+----------+--------+--------+----------+------+----------+------+----------+------------+");
        
        // 显示总金额（对于多个订单）
        if (orders.size() > 1) {
            double total = calculateTotalAmount(orders);
            System.out.printf("| %-76s | %10.2f |%n", "总计:", total);
            System.out.println("+----------+--------+--------+----------+------+----------+------+----------+------------+");
        }
    }

    // 计算单个订单金额
    protected double calculateOrderAmount(Order order) {
        RedWine redWine = redWineService.findById(order.getRedWineId());
        if (redWine != null) {
            return redWine.getPrice() * order.getQuantity();
        }
        return 0;
    }

    // 计算订单集合的总金额
    protected double calculateTotalAmount(List<Order> orders) {
        return orders.stream()
                .mapToDouble(this::calculateOrderAmount)
                .sum();
    }
}
